<?php

namespace app\beautiful\controller\admin\appointment;

use app\BaseController;
use app\beautiful\model\appointment\CommissionModel;
use app\beautiful\model\appointment\CPModel;
use app\beautiful\model\appointment\TechnicianModel;
use think\facade\Db;

class Commission extends BaseController
{
    protected $name = '提成方案';

    public function index()
    {
        $model = new CommissionModel();
        $where = [
            ['shop_id', '=', $this->request->shopId],
        ];
        $name = $this->request->param('name/s');
        if (!empty($name)) {
            $where[] = ['name', 'like', '%'.$name.'%'];
        }
        $commission_id = $this->request->param('commission_id/d', 0);
        if (!empty($commission_id)) {
            $where[] = ['commission_id', '=', $commission_id];
        }
        $res = $model->with(['projects'])->where($where)->select();
        return $this->success($res);
    }

    public function save()
    {
        $commission_id = $this->request->param('commission_id/d', 0);
        $name = $this->request->param('name/s');
        $basic_salary = $this->request->param('basic_salary/f');
        $projects = $this->request->param('projects/s');
        $projects = json_decode($projects, true);
        if (!is_array($projects)) {
            return $this->error('提成规则错误');
        }
        $ids = [];
        foreach ($projects as $item) {
            if ($item['type'] == 0 && ($item['value'] > 1 || $item['value'] < 0)) {
                return $this->error('按比例提成，范围应该为0-1');
            } elseif ($item['type'] == 1 && ($item['value'] > 100000 || $item['value'] < 0)) {
                return $this->error('按固定提成，范围应该为0-100000');
            }
            $ids[] = $item['project_id'];
        }
        $unique = array_unique($ids);
        if (count($unique) != count($ids)) {
            return $this->error('提成规则存在重复项目');
        }

        if (empty($name)) return $this->error('请输入提成方案名称');

        $model = CommissionModel::where([
            ['shop_id', '=', $this->request->shopId],
            ['name', '=', $name],
        ])->find();
        if ($commission_id != 0) {
            if (null !== $model && $model->commission_id != $commission_id) {
                return $this->error('提成方案已存在');
            }
            $model = CommissionModel::where([
                ['commission_id', '=', $commission_id],
            ])->find();

            if (null == $model) {
                return $this->error('修改的提成方案不存在');
            }
            $cp_list = $model->projects()->select();

        } else {
            if (null !== $model) {
                return $this->error('提成方案已存在');
            }
            $model = new CommissionModel();
        }
        $model->name = $name;
        $model->basic_salary = $basic_salary;
        $model->shop_id = $this->request->shopId;
        Db::startTrans();
        try {
            $model->save();
            if ($commission_id != 0) {
                foreach ($projects as $item) {
                    $bool = false;
                    $cpmodel = CPModel::class;
                    foreach ($cp_list as $value) {
                        if ($item['project_id'] == $value->project_id) {
                            $bool = true;
                            $cpmodel = $value;

                            break;
                        }
                    }
                    if (!$bool) {
                        $cpmodel = new CPModel();
                        $cpmodel->project_id = $item['project_id'];
                        $cpmodel->commission_id = $commission_id;
                    }
                    $cpmodel->type = $item['type'];
                    $cpmodel->value = $item['value'];
                    $cpmodel->save();
                }
            } else {
                $list = [];
                foreach ($projects as $item) {
                    $item['commission_id'] = $model->commission_id;
                    $list[] = $item;
                }
                Db::name('beautiful_commission_project')->insertAll($list);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error('操作失败请稍后再试');
        }

        return $this->success(['id' => $model->commission_id]);

    }

    public function del()
    {
        $commission_id = $this->request->param('commission_id/d');
        if (empty($commission_id)) return $this->error('请输入提成方案id');
        $model = CommissionModel::find($commission_id);
        if (null == $model) {
            return $this->error('提成方案不存在');
        }

        $technician = TechnicianModel::where([
            ['commission_id', '=', $commission_id]
        ])->find();
        if (null !== $technician) {
            return $this->error('该提成方案存在员工使用，无法删除');
        }
        Db::startTrans();
        try {
            $list = $model->projects()->select();
            $list->delete();
            $model->delete();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            dump($e);
            // 回滚事务
            Db::rollback();
            return $this->error('操作失败请稍后再试');
        }


        return $this->success([]);

    }

}
